package com.antler.smt.portal.service.impl;

import com.antler.smt.constant.DateTimeConstant;
import com.antler.smt.entity.MemberEntity;
import com.antler.smt.entity.PeopleInfoEntity;
import com.antler.smt.entity.PurchaserEntity;
import com.antler.smt.entity.SupplierEntity;
import com.antler.smt.enums.ResultCodeEnum;
import com.antler.smt.portal.mapper.*;
import com.antler.smt.portal.utils.MailUtil;
import com.antler.smt.portal.utils.RedisUtil;
import com.antler.smt.portal.utils.TokenUtil;
import com.antler.smt.request.portal.*;
import com.antler.smt.response.admin.GetMemberListResp;
import com.antler.smt.response.admin.GetPurchaserListResp;
import com.antler.smt.response.admin.GetSupplierListResp;
import com.antler.smt.response.base.Result;
import com.antler.smt.response.portal.GetPeopleInfoResp;
import com.antler.smt.response.portal.GetPeopleResp;
import com.antler.smt.service.portal.MemberService;
import com.antler.smt.utils.MD5Util;
import com.antler.smt.utils.RandomCodeUtil;
import com.antler.smt.utils.SmsUtil;
import com.antler.smt.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;

/**
 *  TODO
 *  
 *   @author vic
 *   @date 2018-03-25 16:04
 *  
 */
@Service
public class MemberServiceImpl implements MemberService {


    @Autowired
    private MemberInfoMapper memberInfoMapper;

    @Autowired
    private MemberEntityMapper memberEntityMapper;

    @Autowired
    private PurchaserEntityMapper purchaserEntityMapper;

    @Autowired
    private SupplierEntityMapper supplierEntityMapper;

    @Autowired
    private PurchaserInfoMapper purchaserInfoMapper;

    @Autowired
    private SupplierInfoMapper supplierInfoMapper;

    @Autowired
    private PeopleInfoMapper peopleInfoMapper;

    @Autowired
    private PeopleInfoEntityMapper peopleInfoEntityMapper;
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private MailUtil mailUtil;

    /**
     * 会员注册
     *
     * @param request
     * @return
     */
    @Override
    public Result memberRegister(MemberRegisterReq request) {

        Result result = null;
        if (request.getRegisterType() == 1 && StringUtil.isEmpty(request.getPhone())) {
            result = new Result(ResultCodeEnum.REQUEST_PARAM_ERROR);
            result.setMsg("手机号不能为空");
            return result;
        }
        if (request.getRegisterType() == 2 && StringUtil.isEmpty(request.getEmail())) {
            result = new Result(ResultCodeEnum.REQUEST_PARAM_ERROR);
            result.setMsg("邮箱不能为空");
            return result;
        }
        if (request.getRegisterType() == 1) {
            MemberEntity member = memberInfoMapper.selectByMobile(request.getPhone());
            if (member != null) {
                result = new Result(ResultCodeEnum.REQUEST_PARAM_ERROR);
                result.setMsg("该手机号已经被注册");
                return result;
            }
        }
        if (request.getRegisterType() == 2) {
            MemberEntity member = memberInfoMapper.selectByEmail(request.getEmail());
            if (member != null) {
                result = new Result(ResultCodeEnum.REQUEST_PARAM_ERROR);
                result.setMsg("该邮箱已经被注册");
                return result;
            }
        }


        if (request.getRegisterType() == 1) {
            String verCode = redisUtil.get("register::" + request.getPhone());
            if (verCode == null || !verCode.equals(request.getVerificationCode())) {
                result = new Result(ResultCodeEnum.REQUEST_PARAM_ERROR);
                result.setMsg("验证码错误");
                return result;
            }

        }
        if (request.getRegisterType() == 2) {
            String verCode = redisUtil.get("register::" + request.getEmail());
            if (verCode == null || !verCode.equals(request.getVerificationCode())) {
                result = new Result(ResultCodeEnum.REQUEST_PARAM_ERROR);
                result.setMsg("验证码错误");
                return result;
            }
        }
        //插入会员表
        MemberEntity memberEntity = new MemberEntity();
        memberEntity.setCreateTime(new Date());
        memberEntity.setUpdateTime(new Date());
        memberEntity.setEmail(request.getEmail());
        memberEntity.setMobile(request.getPhone());
        memberEntity.setPassword(MD5Util.encryptString(request.getPassword()));
        memberEntity.setType(request.getMemberType());
        memberInfoMapper.insertSelectiveAndGetId(memberEntity);
        long id = memberEntity.getId();

        //如果是服务商注册，插入服务商表
        if (request.getMemberType() == 1) {
            SupplierEntity entity = new SupplierEntity();
            entity.setMemberId(id);
            entity.setCreateTime(new Date());
            supplierEntityMapper.insertSelective(entity);
        }
        //如果是采购商注册，插入采购商表
        else if(request.getMemberType() == 2){
            PurchaserEntity entity = new PurchaserEntity();
            entity.setMemberId(id);
            purchaserEntityMapper.insertSelective(entity);
        }else if(request.getMemberType() == 3){
            //工人
            PeopleInfoEntity peopleInfoEntity = new PeopleInfoEntity();
            peopleInfoEntity.setMemberId(id);
            peopleInfoEntityMapper.insertSelective(peopleInfoEntity);
        }else if(request.getMemberType() == 4){
            //工程师
            PeopleInfoEntity peopleInfoEntity = new PeopleInfoEntity();
            peopleInfoEntity.setMemberId(id);
            peopleInfoEntityMapper.insertSelective(peopleInfoEntity);
        }else if(request.getMemberType() == 5){
            //后期添加线下采购员

        }
        result = new Result(ResultCodeEnum.OPERATION_SUCCESS);
        return result;
    }

    /**
     * 重置密码
     *
     * @param request
     * @return
     */
    @Override
    public Result resetPassword(ResetPasswordReq request) {

        Result result = new Result(ResultCodeEnum.OPERATION_SUCCESS);
        String checked = redisUtil.get("memberCheck::" + request.getMemberId());
        if (checked == null || !"checked".equals(checked)) {
            result = new Result(ResultCodeEnum.REQUEST_PARAM_ERROR);
            result.setMsg("没有通过验证");
            return result;
        }
        MemberEntity entity = memberEntityMapper.selectByPrimaryKey(request.getMemberId());
        entity.setPassword(MD5Util.encryptString(request.getPassword()));
        entity.setUpdateTime(new Date());
        memberEntityMapper.updateByPrimaryKeySelective(entity);
        return result;
    }

    /**
     * 发送注册验证码
     *
     * @param request
     * @return
     */
    @Override
    public Result sendVerCodeForRegister(SendVerCodeForFindPasswordReq request) {
        Result result = null;
        ResultCodeEnum resultCodeEnum = null;
        MemberEntity entity = null;
        if (request.getMethod() == 1) {

            entity = memberInfoMapper.selectByMobile(request.getPhone());
            if (entity != null) {
                resultCodeEnum = ResultCodeEnum.REQUEST_PARAM_ERROR;
                result = new Result(resultCodeEnum, "该手机号已经注册");
                return result;
            }

        } else {
            entity = memberInfoMapper.selectByEmail(request.getEmail());
            if (entity != null) {
                resultCodeEnum = ResultCodeEnum.REQUEST_PARAM_ERROR;
                result = new Result(resultCodeEnum, "该邮箱已经注册");
                return result;
            }
        }
        if (request.getMethod() == 1 && StringUtil.isEmpty(request.getPhone())) {
            result = new Result(ResultCodeEnum.REQUEST_PARAM_ERROR);
            result.setMsg("请输入手机号");
            return result;
        }
        if (request.getMethod() == 2 && StringUtil.isEmpty(request.getEmail())) {
            result = new Result(ResultCodeEnum.REQUEST_PARAM_ERROR);
            result.setMsg("请输入邮箱");
            return result;
        }
        String code = RandomCodeUtil.getRandomNumCode(6);
        if (request.getMethod() == 1) {
            SmsUtil.sendCodeSms(request.getPhone(), code);
            redisUtil.set("register::" + request.getPhone(), code);

        } else {
            mailUtil.sendSimpleMail(request.getEmail(), "易树智造-验证码", code);
            redisUtil.set("register::" + request.getEmail(), code);
        }
        result = new Result();
        return result;
    }

    /**
     * 发送重置密码验证码
     *
     * @param request
     * @return
     */
    @Override
    public Result sendVerCodeForFindPassword(SendVerCodeForFindPasswordReq request) {
        Result result = null;
        ResultCodeEnum resultCodeEnum = null;
        if (request.getMethod() == 1 && StringUtil.isEmpty(request.getPhone())) {
            result = new Result(ResultCodeEnum.REQUEST_PARAM_ERROR);
            result.setMsg("请输入手机号");
            return result;
        }
        if (request.getMethod() == 2 && StringUtil.isEmpty(request.getEmail())) {
            result = new Result(ResultCodeEnum.REQUEST_PARAM_ERROR);
            result.setMsg("请输入邮箱");
            return result;
        }
        MemberEntity entity = null;

        String code = RandomCodeUtil.getRandomNumCode(6);
        if (request.getMethod() == 1) {

            entity = memberInfoMapper.selectByMobile(request.getPhone());
            if (entity == null) {
                resultCodeEnum = ResultCodeEnum.REQUEST_PARAM_ERROR;
                result = new Result(resultCodeEnum, "该手机号没有注册");
                return result;
            }
            SmsUtil.sendCodeSms(request.getPhone(), code);
            redisUtil.set("findPassword::" + entity.getId(), code);

        } else {
            entity = memberInfoMapper.selectByEmail(request.getEmail());
            mailUtil.sendSimpleMail(request.getEmail(), "易树智造-验证码", code);
            if (entity == null) {
                resultCodeEnum = ResultCodeEnum.REQUEST_PARAM_ERROR;
                result = new Result(resultCodeEnum, "该邮箱没有注册");
                return result;
            }

            redisUtil.set("findPassword::" + entity.getId(), code);
        }
        HashMap hashMap = new HashMap();
        hashMap.put("memberId", entity.getId());
        result = new Result(hashMap);
        return result;
    }

    /**
     * 检验找回密码验证码
     *
     * @param request
     * @return
     */
    @Override
    public Result checkVerCode(CheckVerCodeReq request) {
        ResultCodeEnum resultCodeEnum = null;
        Result result = null;
        String code = redisUtil.get("findPassword::" + request.getMemberId());
        if (StringUtil.isEmpty(code)) {
            resultCodeEnum = ResultCodeEnum.REQUEST_PARAM_ERROR;
            result = new Result(resultCodeEnum, "没有获取验证码");
            result.setMsg("没有获取验证码");
            return result;
        }
        if (code.equals(request.getVerCode())) {
            resultCodeEnum = ResultCodeEnum.OPERATION_SUCCESS;
            redisUtil.set("memberCheck::" + request.getMemberId(), "checked");
            result = new Result(resultCodeEnum);
        } else {
            resultCodeEnum = ResultCodeEnum.QUERY_DATA_ERROR;
            result = new Result(resultCodeEnum, "验证码错误");
        }
        return result;
    }

    /**
     * 会员登录
     *
     * @param request
     * @return
     */
    @Override
    public Result memberLogin(MemberLoginReq request, HttpServletResponse response) {

        String userName = request.getUserName();
        boolean isNum = StringUtil.isNumeric(userName);
        MemberEntity entity = null;
        if (!isNum) {
            entity = memberInfoMapper.selectByEmail(userName);
        } else {
            entity = memberInfoMapper.selectByMobile(userName);
            if (entity == null) {
                entity = memberEntityMapper.selectByPrimaryKey(Long.parseLong(userName));
            }
        }
        Result result = null;
        if (entity == null) {
            result = new Result(ResultCodeEnum.QUERY_DATA_ERROR, "用户不存在");
        } else {
            if (!entity.getPassword().equals(MD5Util.encryptString(request.getPassword()))) {
                result = new Result(ResultCodeEnum.QUERY_DATA_ERROR, "密码错误");
            } else if (entity.getType() != request.getType()) {
                result = new Result(ResultCodeEnum.QUERY_DATA_ERROR, "会员类型错误");
            } else if (entity.getStatus() != null && entity.getStatus() == 1) {
                result = new Result(ResultCodeEnum.QUERY_DATA_ERROR, "会员已经被冻结，请联系管理员解冻");
            } else {
                HashMap hashMap = new HashMap();

                String token = TokenUtil.getTokenByMember(entity);
                //是否登录标记
                Cookie cookie = new Cookie("token", token);
                cookie.setMaxAge((int) DateTimeConstant.WEEK_S);
                cookie.setPath("/");
                //供应商还是服务商，1服务商 2采购商
                Cookie typeCookie = new Cookie("memberType", entity.getType().toString());
                typeCookie.setMaxAge((int) DateTimeConstant.WEEK_S);
                typeCookie.setPath("/");
                //会员姓名
                Cookie nickNameCookie = new Cookie("nickName", entity.getNickName().toString());
                nickNameCookie.setMaxAge((int) DateTimeConstant.WEEK_S);
                nickNameCookie.setPath("/");
                //是否已经认证
                Integer isAuthed = 0;
                if (entity.getType() == 1) {
                    SupplierEntity searchEntity = new SupplierEntity();
                    searchEntity.setMemberId(entity.getId());
                    GetSupplierListResp getSupplierListResp = supplierInfoMapper.selectSupplierByKey(searchEntity);

                    if (getSupplierListResp != null) {
                        isAuthed = getSupplierListResp.getSettledAuditResult();
                    }
                } else if(entity.getType() == 2){
                    GetPurchaserListResp getPurchaserListResp = purchaserInfoMapper.selectByMemberId(entity.getId());
                    if (getPurchaserListResp != null) {
                        isAuthed = getPurchaserListResp.getAuditResult();
                    }
                }else if(entity.getType() == 3){
                    PeopleInfoEntity peopleInfoEntity = peopleInfoMapper.selectPeople(entity.getId());
                    if(null != peopleInfoEntity){
                        isAuthed = peopleInfoEntity.getStatus();
                    }
                }else if(entity.getType() == 4){
                    PeopleInfoEntity peopleInfoEntity = peopleInfoMapper.selectPeople(entity.getId());
                    if(null != peopleInfoEntity){
                        isAuthed = peopleInfoEntity.getStatus();
                    }
                }else if(entity.getType() == 5){

                }
                Cookie isAuthedCookie = new Cookie("isAuthed", String.valueOf(isAuthed));
                isAuthedCookie.setMaxAge((int) DateTimeConstant.WEEK_S);
                isAuthedCookie.setPath("/");
                response.addCookie(cookie);
                response.addCookie(typeCookie);
                response.addCookie(isAuthedCookie);
                response.addCookie(nickNameCookie);
                entity.setLastLoginTime(new Date());
                memberEntityMapper.updateByPrimaryKeySelective(entity);
                result = new Result(hashMap);
            }
        }
        return result;
    }

    /**
     * 获取当前会员实体
     *
     * @param memberId
     * @return
     */
    @Override
    public Result<GetMemberListResp> getMemberInfo(long memberId) {
        Result result = null;
        GetMemberListResp memberInfo = memberInfoMapper.getMemberInfo(memberId);
        result = new Result(memberInfo);
        return result;
    }

}
